package com.youcheng.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;


@Component
public final class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void remove(String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }

    @SuppressWarnings("all")
    public boolean exists(String key) {
        if(key == null){
            return false;
        }
        return redisTemplate.hasKey(key);
    }

    /**
     * 从redis中获取key对应的过期时间;
     * 如果该值有过期时间，就返回相应的过期时间;
     * 如果该值没有设置过期时间，就返回-1;
     * 如果没有该值，就返回-2;
     */
    public Long ttl(String key){
        return redisTemplate.opsForValue().getOperations().getExpire(key);
    }


    public boolean set(String key , Object value, Long expireTime){
        boolean result = false;
        try {
            redisTemplate.opsForValue().set(key , value);
            redisTemplate.expire(key , expireTime , TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public Object get(String key){
        return key==null?null:redisTemplate.opsForValue().get(key);
    }



}
